package srcInterviewPrep;

public final class StockSeller
{
    public static void PrintBuySellDates(double[] prices)
    {
        PrintBuySellDatesTailRecursive(prices, 0, 0, 0);
    }
    
    private static void PrintBuySellDatesTailRecursive(
        double[] prices,
        int startIndex,
        int buyDate,
        int sellDate)
    {
        if (startIndex == prices.length)
        {
            System.out.println("buy: " + prices[buyDate]);
            System.out.println("sell: " + prices[sellDate]);
            System.out.println("max value: " + (prices[sellDate] - prices[buyDate]));
            
            return;
        }
        
        int curMax = startIndex;
        int nextStartIndex = startIndex + 1;
        
        for (int i = startIndex + 1; i < prices.length; ++i)
        {
            if (prices[i] > prices[curMax])
            {
                curMax = i;
            }
            else if (prices[i] < prices[startIndex])
            {
                nextStartIndex = i;
            }
        }
        
        if (prices[sellDate] - prices[buyDate] 
            < prices[curMax] - prices[startIndex])
        {
            buyDate = startIndex;
            sellDate = curMax;
        }
        
        PrintBuySellDatesTailRecursive(prices, nextStartIndex, buyDate, sellDate);
    }
}
